package fm.dongman.animefm.view.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.bumptech.glide.Glide
import fm.dongman.animefm.R
import fm.dongman.animefm.contractlib.IModel
import fm.dongman.animefm.contractlib.contract.ComicClassifyContract
import fm.dongman.animefm.contractlib.model.ClassifyDataModel
import fm.dongman.animefm.view.activity.SingleActivity
import fm.dongman.animefm.view.listener.LoadMoreRecyclerOnScrollListener
import fm.dongman.animefm.view.transform.GlideRoundTransform
import fm.dongman.animefm.view.util.ActivityHelper
import fm.dongman.animefm.view.util.SystemHelper
import fm.dongman.animefm.view.util.ToastHelper
import fm.dongman.animefm.view.widget.ClassifyView
import fm.dongman.animefm.view.widget.ClassifyView.ComicClassifyAdapter
import fm.dongman.animefm.view.widget.MultiStateLayout
import fm.dongman.modellib.StaticArea.Injection
import fm.dongman.modellib.model.ComicModel
import fm.dongman.presenterlib.presenter.ComicClassifyPresenter
import kotlinx.android.synthetic.main.fragment_comic_classify.*
import kotlinx.android.synthetic.main.item_comic_classify.view.*
import org.jetbrains.anko.onClick

/**
 * 番剧分类界面
 * Created by shize on 2017/10/24.
 */
class ComicClassifyFragment : BaseFragment(), ComicClassifyContract.IComicClassifyView {
    private val mTypeList = listOf("地区", "类型", "时间", "状态", "篇幅")

    private lateinit var mPresenter: ComicClassifyContract.IComicClassifyPresenter // 全局控制器

    private lateinit var mCountryAdapter: ComicClassifyAdapter  // 国家
    private var mCountries: ArrayList<ClassifyDataModel.TypeData> = ArrayList() // 国家集合

    private lateinit var mTypeAdapter: ComicClassifyAdapter  // 类型
    private var mTypes: ArrayList<ClassifyDataModel.TypeData> = ArrayList() // 类型集合

    private lateinit var mTimeAdapter: ComicClassifyAdapter  // 时间
    private var mTime: ArrayList<ClassifyDataModel.TypeData> = ArrayList() // 时间集合

    private lateinit var mStateAdapter: ComicClassifyAdapter // 状态
    private var mStates: ArrayList<ClassifyDataModel.TypeData> = ArrayList() // 状态集合

    private lateinit var mSizeAdapter: ComicClassifyAdapter  // 篇幅
    private var mSizes: ArrayList<ClassifyDataModel.TypeData> = ArrayList() // 篇幅集合

    private var mFilter: ClassifyDataModel.ClassifyFilter = ClassifyDataModel.ClassifyFilter() // 过滤器

    private lateinit var mComicsAdapter: ComicClassifyComicsAdapter // 番剧列表适配器
    private var mResultComics: ArrayList<IModel.IComicModel> = ArrayList() // 过滤后的番剧列表

    /**  滑动监听器 */
    private lateinit var mScrollListener:LoadMoreRecyclerOnScrollListener

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val view = inflater!!.inflate(R.layout.fragment_comic_classify, container, false)
        ComicClassifyPresenter(this, Injection.provideComicClassifyRepository())
        return view
    }

    override fun initData() {
        onStateChanged(MultiStateLayout.LOADING)
        mPresenter.startLoad()
    }

    override fun bindData() {
        bindToolbar()
        // 设置分类管理器
        bindClassifyManager()
        // 设置番剧列表
        bindComicListRecycler()
    }

    /**
     * 绑定 toolbar
     */
    private fun bindToolbar() {
        //设置Toolbar padding
        mComicClassifyToolbar.setPadding(0, SystemHelper.getStatusBarHeight(activity), 0, 0)
        //返回按钮
        mComicClassifyToolbar.setNavigationOnClickListener {
            ActivityHelper.backActivity(activity)
        }
    }

    /**
     * 绑定过滤器控件
     */
    private fun bindClassifyManager() {
        mCountryAdapter = ComicClassifyAdapter(activity, mCountries)
        mCountryAdapter.setOnItemClickListener(object : ClassifyView.OnItemClickListener {
            override fun onClick(key: ClassifyDataModel.TypeData) {
                mFilter.country = key.id
                submitSelected(key)
            }
        })
        mTypeAdapter = ComicClassifyAdapter(activity, mTypes)
        mTypeAdapter.setOnItemClickListener(object : ClassifyView.OnItemClickListener {
            override fun onClick(key: ClassifyDataModel.TypeData) {
                mFilter.type = key.id
                submitSelected(key)
            }
        })
        mTimeAdapter = ComicClassifyAdapter(activity, mTime)
        mTimeAdapter.setOnItemClickListener(object : ClassifyView.OnItemClickListener {
            override fun onClick(key: ClassifyDataModel.TypeData) {
                mFilter.time = key.id
                submitSelected(key)
            }
        })
        mStateAdapter = ComicClassifyAdapter(activity, mStates)
        mStateAdapter.setOnItemClickListener(object : ClassifyView.OnItemClickListener {
            override fun onClick(key: ClassifyDataModel.TypeData) {
                mFilter.state = key.id
                submitSelected(key)
            }
        })
        mSizeAdapter = ComicClassifyAdapter(activity, mSizes)
        mSizeAdapter.setOnItemClickListener(object : ClassifyView.OnItemClickListener {
            override fun onClick(key: ClassifyDataModel.TypeData) {
                mFilter.size = key.id
                submitSelected(key)
            }
        })
        mClassifyView.setDataSource(mTypeList, listOf(mCountryAdapter, mTypeAdapter, mTimeAdapter,
                mStateAdapter, mSizeAdapter))
    }

    /**
     * 提交选中的参数
     * @param key 选中的类型
     */
    private fun submitSelected(key: ClassifyDataModel.TypeData) {
        mClassifyView.setTypeText(key.name)
        mPresenter.getComicList(1, mFilter)
    }

    /**
     * 绑定番剧列表控件
     */
    private fun bindComicListRecycler() {
        mComicListRecycler.layoutManager = GridLayoutManager(activity, 3,
                GridLayoutManager.VERTICAL, false)
        mComicsAdapter = ComicClassifyComicsAdapter(activity, mResultComics)
        mComicListRecycler.adapter = mComicsAdapter
        // 设置滑动加载监听器
        mScrollListener = object : LoadMoreRecyclerOnScrollListener(mComicListRecycler.layoutManager) {
            override fun onLoadMore(currentPage: Int) {
                mPresenter.getComicList(currentPage, mFilter)
            }
        }
        mComicListRecycler.addOnScrollListener(mScrollListener)
    }

    override fun setPresenter(presenter: ComicClassifyContract.IComicClassifyPresenter) {
        mPresenter = presenter
    }

    override fun isActive(): Boolean {
        return isAdded
    }

    override fun getViewContext(): Context {
        return activity
    }

    override fun showNoNetwork() {
        onStateChanged(MultiStateLayout.NET_ERROR)
    }

    override fun showRefreshFailed() {
        ToastHelper.getInstance(activity).showError("动漫分类页面加载失败！")
    }

    override fun showClassifyCountry(country: List<ClassifyDataModel.TypeData>) {
        // 获取全部番剧
        mPresenter.getComicList(1, mFilter)
        mCountries.clear()
        mCountries.addAll(country)
        mCountryAdapter.notifyDataSetChanged()
    }

    override fun showClassifyType(types: List<ClassifyDataModel.TypeData>) {
        mTypes.clear()
        mTypes.addAll(types)
        mTypeAdapter.notifyDataSetChanged()
    }

    override fun showClassifyTime(time: List<ClassifyDataModel.TypeData>) {
        mTime.clear()
        mTime.addAll(time)
        mTimeAdapter.notifyDataSetChanged()
    }

    override fun showClassifyState(states: List<ClassifyDataModel.TypeData>) {
        mStates.clear()
        mStates.addAll(states)
        mStateAdapter.notifyDataSetChanged()
    }

    override fun showClassifySize(sizes: List<ClassifyDataModel.TypeData>) {
        mSizes.clear()
        mSizes.addAll(sizes)
        mSizeAdapter.notifyDataSetChanged()
    }

    override fun showComicList(comics: List<IModel.IComicModel>) {
        onStateChanged(MultiStateLayout.SUCCESS)
        mResultComics.clear()
        mResultComics.addAll(comics)
        mComicsAdapter.notifyDataSetChanged()
        // 设置下拉加载更多，更换条件时，需要重新设置页数
        mScrollListener.clearPage()
    }

    override fun showMoreComicList(comics: List<IModel.IComicModel>) {
        mResultComics.addAll(comics)
        mComicsAdapter.notifyDataSetChanged()
    }

    /**
     * 改变状态
     * @param state 状态值
     */
    private fun onStateChanged(state: Int) {
        mClassifyMultiState.changeState(state)
    }

    companion object {
        fun getInstance(): ComicClassifyFragment {
            return ComicClassifyFragment()
        }
    }

    /**
     * 番剧列表适配器
     */
    private class ComicClassifyComicsAdapter constructor(private val mContext: Context, private val mData: List<IModel.IComicModel>)
        : RecyclerView.Adapter<ComicClassifyViewHolder>() {

        @SuppressLint("InflateParams")
        override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ComicClassifyViewHolder =
                ComicClassifyViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_comic_classify, null))

        @SuppressLint("SetTextI18n")
        override fun onBindViewHolder(holder: ComicClassifyViewHolder?, position: Int) {
            val comic = mData[position] as ComicModel
            holder!!.mComicName.text = comic.title
            holder.mComicState.text = "更新至${comic.episodes}集"
            Glide.with(mContext).load(comic.imgUrl).centerCrop()
                    .transform(GlideRoundTransform(mContext, 4)).into(holder.mComicImage)
            holder.itemView.onClick {
                ActivityHelper.startActivity(mContext as Activity, SingleActivity::class.java, mapOf(
                        Pair(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_ANIME_INFO),
                        Pair(SingleActivity.BUNDLE_EXTRA_KEY_ID, comic.id)), false)
            }
        }

        override fun getItemCount(): Int = mData.size
    }

    /**
     * 番剧列表 ViewHolder
     */
    class ComicClassifyViewHolder constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val mComicImage: ImageView = itemView.mItemClassifyImage // 动漫图片
        val mComicName: TextView = itemView.mItemClassifyTitle // 动漫名称
        val mComicState: TextView = itemView.mItemClassifySubTitle // 动漫状态，更新集数
    }
}